package com.snackshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.snackshop.mapper.UserMapper;
import com.snackshop.pojo.bo.UserBO;
import com.snackshop.pojo.model.User;
import lombok.extern.java.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

@Log
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String userPhone) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_phone", userPhone);
        User user = userMapper.selectOne(wrapper);
        UserBO userBO = new UserBO();
        BeanUtils.copyProperties(user, userBO);
        // 授权（应该到数据库查询权限）
        // redis里存放一份
        GrantedAuthority authority = new SimpleGrantedAuthority("sys:user:test");
        Set<GrantedAuthority> authorities = Set.of(authority);
        userBO.setAuthorities(authorities);
        return userBO;
    }
}
